<script setup lang="ts">
import { Swiper, SwiperSlide } from 'swiper/vue/swiper-vue'
import { onMounted, onUnmounted, ref } from 'vue'
import { chunk, uniq } from 'lodash'
import { series, tooltip, windowResize, xAxis, yAxis } from '@/views/common'
import * as echarts from 'echarts'
import { ECharts } from 'echarts'
import { qkLoopRequest, qkStudyRequest, qkYearRequest } from '@/views/cockpit/projectSection/api'
import moment from 'moment/moment'
import { isSuccess } from '@/views/cockpit/common'
import { Autoplay } from 'swiper'
import { fontSizeRem } from '@/utils/utils'
enum tableProp {
  desc = 'desc',
  year = 'year',
  process = 'process',
  delay = 'delay',
  stop = 'stop',
}
type TableData = {
  [key in Exclude<tableProp, tableProp.desc>]: string | number
} & {
  [tableProp.desc]?: string
}
enum loopKey {
  projectName = 'projectName',
  ratio = 'num',
  time = 'startTime',
}
type LoopData = {
  [key in loopKey]: string
}

const lineHeight: number = 50
const loopYear = ref<string>(moment().format('YYYY'))
const loopResult = ref<LoopData[][]>([])
const getLoopData = () => {
  loopResult.value = []
  qkLoopRequest(loopYear.value).then((res) => {
    if (isSuccess(res)) {
      const el: Element = document.getElementsByClassName('swiperContent')[0]
      let height: number = 0
      let chunkNum: number = 0
      if (el) {
        height = el.clientHeight
        chunkNum = Math.floor(height / lineHeight)
      }
      // TODO - 完成度字段未返回
      const data = (res.data.data || []) as LoopData[]
      loopResult.value = chunk(data, chunkNum)
    }
  })
}
// 获取表格数据
const tableData = ref<TableData[]>([])
const tableTd = ref<(string | number)[]>([])
const getTableData = () => {
  qkYearRequest().then((res) => {
    if (isSuccess(res)) {
      // project_year
      const oldData = (res.data.data || []).sort((prev, next) => {
        return prev.project_year - next.project_year
      })
      const yearData = uniq(oldData.map((t) => t.project_year) || [])
      const data: TableData[] = []
      const processTxt = '在研项目'
      const delayTxt = '延期项目'
      const stopTxt = '结题项目'
      for (let i = 0; i < yearData.length; i++) {
        const list = oldData.filter((t) => t.project_year === yearData[i])
        const process: number = list.filter((t) => t.type === processTxt)[0]?.num || 0
        const delay: number = list.filter((t) => t.type === delayTxt)[0]?.num || 0
        const stop: number = list.filter((t) => t.type === stopTxt)[0]?.num || 0
        data.push({ year: yearData[i] + '年', process, delay, stop })
      }
      const viewData: any[] = [
        { desc: `${processTxt} (个)` },
        { desc: `${delayTxt} (个)` },
        { desc: `${stopTxt} (个)` },
      ]
      for (let i = 0; i < data.length; i++) {
        tableTd.value.push(data[i].year)
        const key = 'td' + i
        viewData[0][key] = data[i][tableProp.process]
        viewData[1][key] = data[i][tableProp.delay]
        viewData[2][key] = data[i][tableProp.stop]
      }
      tableData.value = viewData
    }
  })
}
const studyYear = ref<string>(moment().format('YYYY'))
const barEl = ref<HTMLDivElement>()
let barChat: ECharts
const initChat = () => {
  qkStudyRequest(studyYear.value).then((res) => {
    if (isSuccess(res)) {
      const data = res.data.data || []
      const lineX = data.map((t) => t.type) || []
      const lineY1 = data.map((t) => t.num1) || []
      const lineY2 = data.map((t) => t.num2) || []
      if (barChat) barChat.clear()
      barChat = echarts.init(barEl.value)
      barChat.setOption({
        tooltip,
        grid: {
          top: '80',
          left: '0',
          right: '2',
          bottom: '0',
          containLabel: true,
        },
        legend: {
          itemWidth: 14,
          textStyle: {
            color: '#fff',
          },
          top: '5%',
          left: '20%',
        },
        xAxis: {
          axisPointer: {
            type: 'shadow',
          },
          ...xAxis(lineX, false, lineX.length),
        },
        yAxis: yAxis(false),
        color: ['#0272FC', '#A53976'],
        series: [
          {
            ...series(lineY1, '#0272FC', '计划数'),
            barWidth: fontSizeRem(0.3),
            itemStyle: {
              // color: '#C7A746',
              color: function (params) {
                //展示正值的柱子，负数设为透明
                let colorArr = params.value > 0 ? ['#0272FC', '#08103B'] : ['#08103B', '#0272FC']
                return new echarts.graphic.LinearGradient(
                  0,
                  0,
                  0,
                  1,
                  [
                    {
                      offset: 0,
                      color: colorArr[0], // 0% 处的颜色
                    },
                    {
                      offset: 1,
                      color: colorArr[1], // 100% 处的颜色
                    },
                  ],
                  false
                )
              },
              barBorderRadius: [30, 30, 0, 0],
            },
            label: {
              show: true,
              position:'top',
            },
          },
          {
            ...series(lineY2, '#A53976', '完成数'),
            barWidth: fontSizeRem(0.3),
            label: {
              show: true,
              position:'top',
            },
            itemStyle: {
              // color: '#C7A746',
              color: function (params) {
                //展示正值的柱子，负数设为透明
                let colorArr = params.value > 0 ? ['#A53976', '#08103B'] : ['#08103B', '#A53976']
                return new echarts.graphic.LinearGradient(
                  0,
                  0,
                  0,
                  1,
                  [
                    {
                      offset: 0,
                      color: colorArr[0], // 0% 处的颜色
                    },
                    {
                      offset: 1,
                      color: colorArr[1], // 100% 处的颜色
                    },
                  ],
                  false
                )
              },
              barBorderRadius: [30, 30, 0, 0],
            },
          },
        ],
      })
    }
  })
}
const windowEvent = () => {
  windowResize(300, () => {
    if (barChat) barChat.resize()
  })
}
onMounted(() => {
  getLoopData()
  getTableData()
  initChat()
  window.addEventListener('resize', () => {
    windowEvent()
  })
})
onUnmounted(() => {
  window.removeEventListener('resize', windowEvent)
})
</script>

<template>
  <div class="chartContent">
    <div class="project">
      <div class="study mb20">
        <div class="modal">
          <span class="modalTitle l10">知识产权 (在研)</span>
          <div class="searchItem searchRight">
            <el-date-picker
              v-model="studyYear"
              type="year"
              placeholder="请选择"
              value-format="YYYY"
              format="YYYY"
              clearable
              @change="initChat"
            />
          </div>
          <div ref="barEl" class="chat"></div>
        </div>
      </div>
      <div class="process">
        <el-table :data="tableData" border class="processTable">
          <el-table-column prop="desc" label="立项年度" min-width="100px" />
          <el-table-column
            v-for="(item, index) in tableTd"
            :key="'td' + index"
            :prop="'td' + index"
            :label="item"
            min-width="100px"
          />
        </el-table>
      </div>
    </div>
    <div class="ranking">
      <div class="searchItem searchRight">
        <el-date-picker
          v-model="loopYear"
          type="year"
          placeholder="选择年度"
          value-format="YYYY"
          format="YYYY"
          clearable
          @change="getLoopData"
        />
      </div>
      <div class="modalTitle">项目执行情况</div>
      <div class="rankContent">
        <div class="rankLi head">
          <div class="item">
            <div class="td"><span class="txt">立项时间</span></div>
            <div class="td"><span class="txt">项目名称</span></div>
            <div class="td"><span class="txt">完成度</span></div>
          </div>
        </div>
        <!-- :modules="[Autoplay]"
              :autoplay="{delay: 6000, disableOnInteraction: false}" loop-->
        <swiper class="swiperContent" direction="vertical">
          <swiper-slide v-for="(slide, index) in loopResult" :key="index + 'slide'">
            <div class="rankLi body">
              <div class="item" v-for="(option, idx) in slide" :key="index + 'slide' + idx">
                <div class="td" :title="option.startTime || ''">
                  <span class="txt">{{ option.startTime }}</span>
                </div>
                <div class="td" :title="option.projectName || ''">
                  <span class="txt">{{ option.projectName }}</span>
                </div>
                <div class="td" :title="option.num || ''">
                  <span class="txt">{{ option.num }}</span>
                </div>
              </div>
            </div>
          </swiper-slide>
        </swiper>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
@import '@/assets/css/theme';
@import '../../common';
.chartContent {
  .project {
    overflow: hidden;
    display: flex;
    flex-direction: column;
    flex: 1 1 0;
    background-image: url(../../img/project-bg.png);
    background-size: 100% 100%;
    .study {
      display: flex;
      flex: 1 1 0;
      .modal {
        position: relative;
        display: flex;
        flex: 1 1 0;
        padding: 10px;
        // border: 1px solid $primary-color;
      }
      .searchRight {
        position: absolute;
      }
      .searchYear {
        // position: absolute;
      }
    }
    .process {
      display: flex;
      align-items: flex-end;
      height: 240px;
      margin: 2vh;
      .processTable {
        background-color: transparent !important;
        :deep {
          th {
            background-color: #0b215b !important;
          }
          tr {
            background-color: transparent !important;
            &:hover > td {
              background-color: transparent !important;
            }
          }
          th,
          td {
            height: 55px !important;
            color: #fff;
            font-size: 16px;
          }
        }
      }
      .el-table{
        --el-table-border: 1px solid #2A4287 !important;
        --el-table-border-color: #2A4287 !important
      }
      :deep(.el-table th.is-leaf){
        border: 1px solid #2A4287 !important
      }
    }
  }
  .ranking {
    background-image: url(../../img/ranking-bg.png);
    background-size: 100% 100%;
  }
  .rankContent {
    .rankLi {
      .item {
        .td {
          width: 33%;
          min-width: 33%;
          max-width: 33%;
        }
      }
    }
  }
}
</style>
